package lobby

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"webcppcluster/account"
	"webcppcluster/cache"
	"webcppcluster/config"
	"webcppcluster/db"
	"webcppcluster/service"
)

// GetMoney 获取用户金钱（保证缓存存在）
func GetMoney(userid int64, store *cache.RedisStore) int {
	strKey := fmt.Sprintf(config.KeyPackage, fmt.Sprintf("%d", userid))
	
	if store.Exists(strKey) {
		moneyStr, err := store.GetHashField(strKey, fmt.Sprintf("%d", config.IDMoney))
		if err == nil {
			money, _ := strconv.Atoi(moneyStr)
			return money
		}
	}

	// 从数据库获取
	items, err := db.GetPackageIdAndNum(userid)
	if err == nil {
		for _, item := range items {
			if item.PropID == config.IDMoney {
				// 初始化缓存
				now := time.Now()
				account.InitPackage(userid, now, store)
				return item.PropNum
			}
		}
	}

	return 0
}

// GetMonday 获取周一日期
func GetMonday(today time.Time) string {
	// 计算周一的日期
	weekday := int(today.Weekday())
	if weekday == 0 {
		weekday = 7 // 星期天算作第7天
	}
	monday := today.AddDate(0, 0, -(weekday - 1))
	return monday.Format("2006_01_02")
}

// SendMail 发送邮件
func SendMail(mailinfo map[string]interface{}, store *cache.RedisStore) error {
	// 这里需要protobuf支持，暂时简化实现
	// 实际应该使用proto.Mail结构
	
	// 安全获取参数
	useridListInterface, ok := mailinfo["useridlist"]
	if !ok {
		return fmt.Errorf("useridlist is required")
	}
	useridList, ok := useridListInterface.([]string)
	if !ok {
		return fmt.Errorf("useridlist must be []string")
	}
	
	title, _ := mailinfo["title"].(string)
	context, _ := mailinfo["context"].(string)
	
	mailTypeInt, ok := mailinfo["type"]
	var mailType int
	if ok {
		switch v := mailTypeInt.(type) {
		case int:
			mailType = v
		case float64:
			mailType = int(v)
		case string:
			mailType, _ = strconv.Atoi(v)
		}
	}
	
	attach, _ := mailinfo["attach"].(map[string]interface{})
	buttontext, _ := mailinfo["buttontext"].(string)
	
	fromuseridInt, ok := mailinfo["fromuserid"]
	var fromuserid int64
	if ok {
		switch v := fromuseridInt.(type) {
		case int64:
			fromuserid = v
		case int:
			fromuserid = int64(v)
		case float64:
			fromuserid = int64(v)
		case string:
			fromuserid, _ = strconv.ParseInt(v, 10, 64)
		}
	}

	// 验证道具
	validAttach := make(map[string]int)
	for propidStr, propnum := range attach {
		propid, _ := strconv.Atoi(propidStr)
		if _, ok := config.ShopCfg[propid]; ok {
			if num, ok := propnum.(float64); ok {
				validAttach[propidStr] = int(num)
			} else if num, ok := propnum.(int); ok {
				validAttach[propidStr] = num
			}
		}
	}

	attachJSON, _ := json.Marshal(validAttach)
	buttontextEncoded := base64.StdEncoding.EncodeToString([]byte(buttontext))

	// 构建proto数据（简化版，实际需要使用protobuf）
	// 这里需要根据proto定义来序列化
	mailData := map[string]interface{}{
		"userid":     convertStringListToInt64List(useridList),
		"title":      title,
		"context":    context,
		"type":       mailType,
		"attach":     string(attachJSON),
		"buttontext": buttontextEncoded,
		"fromuserid": fromuserid,
	}

	// 发送给C++邮件服务器（实际应该使用protobuf序列化）
	data, _ := json.Marshal(mailData)
	return service.SendSvrd(config.MailHost, config.MailPort, data)
}

// convertStringListToInt64List 转换字符串列表为int64列表
func convertStringListToInt64List(strList []string) []int64 {
	result := make([]int64, len(strList))
	for i, s := range strList {
		result[i], _ = strconv.ParseInt(s, 10, 64)
	}
	return result
}

// GetMailList 获取邮件列表
func GetMailList(userid int64, store *cache.RedisStore) []map[string]interface{} {
	strKeyList := fmt.Sprintf(config.KeyMailList, userid)
	mailidlist, _ := store.LRange(strKeyList, 0, -1)
	
	mailinfolist := []map[string]interface{}{}
	for _, mailid := range mailidlist {
		strKey := fmt.Sprintf(config.KeyMailDetail, mailid)
		res, err := store.GetHash(strKey)
		if err != nil || len(res) == 0 {
			store.LRem(strKeyList, 1, mailid)
			continue
		}
		// 拼邮件信息
		mailinfo := make(map[string]interface{})
		for k, v := range res {
			mailinfo[k] = v
		}
		mailinfolist = append(mailinfolist, mailinfo)
	}
	return mailinfolist
}

